package com.ruoyi.web.controller.basedata;

import com.ruoyi.basedata.domain.TerminalDbCommand;
import com.ruoyi.basedata.domain.vo.TerminalsDbProtocol;
import com.ruoyi.basedata.service.ITerminalsDbService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.datastatistics.service.ITerminalDbCommandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/dbCommand")
public class TerminalDbCommandController extends BaseController {
    @Resource
    private Environment env;
    @Autowired
    private ITerminalDbCommandService terminalDbCommandService;
    @Autowired
    private ITerminalsDbService terminalsDbService;


    @PostMapping("/terminalDbCommand")
    @PreAuthorize("@ss.hasPermi('basedata:termianldb:terminalDbCommand')")

    public AjaxResult terminalDbCommand(@RequestBody TerminalDbCommand terminalDbCommand) {
        try {
            TerminalsDbProtocol terminalsDbProtocol = new TerminalsDbProtocol();
            terminalsDbProtocol.setSupplierId(terminalDbCommand.getSupplierId());
            terminalsDbProtocol.setTerminalId(terminalDbCommand.getTerminalCode());
            List<TerminalsDbProtocol> terminalsDbProtocols = terminalsDbService.selectTerminalsDbProtocolList(terminalsDbProtocol);
            if (terminalsDbProtocols == null || terminalsDbProtocols.size()<1) {
                return AjaxResult.error("该设备不存在");
            }
            terminalsDbProtocol = terminalsDbProtocols.get(0);
            String communicationType = DictUtils.getDictLabel("communication_type", terminalsDbProtocol.getCommunicationType());
            String url = env.getProperty("netty-url." + communicationType + "." + "requestNetty");
            return terminalDbCommandService.terminalDbCommandPush(terminalDbCommand.getSupplierId(),terminalsDbProtocol,terminalDbCommand.getCommandType(),terminalDbCommand.getValues(),url);

        } catch (Exception exception) {
            logger.error("系统异常",exception);
            return error("系统异常");
        }
    }
}
